const fs = require('fs')
const puppeteer = require('puppeteer')
const json2xls =  require('json2xls')
// const stocks = require('./stock-match.json')
const stocks = require('./good-match.json')
const list = []
const maxPE = 41;
async function main() {
    // Do something
    const browser = await puppeteer.launch({
        headless: true,
    })

    const page = await browser.newPage()
    try {
        for (let i = 0; i < stocks.length; i++) {
            const stockId = stocks[i]
            const url = `https://xueqiu.com/S/${stockId}`
            console.log(i + 1, ':', stockId)
            await page.goto(url)
            const item = await page.evaluate(() => {
                const name = document.getElementsByClassName('stock-name')[0].innerText.split('(')[0]
                const price = document.getElementsByClassName('stock-current')[0].innerText.replace(/[$¥HK]/gi,'')
                const stockChange = document.getElementsByClassName('stock-change')[0].innerText.split(' ')
                const info = document.getElementsByClassName('quote-info')[0].innerText.replace(/\n/gi, '\t').split('\t').reduce((obj, el) => { const [key, value] = el.split('：'); obj[key] = value; return obj; }, {})
                info['股票名称'] = name
                info['当前股价'] = price
                info['今日涨幅'] = stockChange[1].replace('%', '')
                info['']
                return info
            })
            item['股票代码'] = stockId
            const PEJ = parseFloat(item['市盈率(静)'])
            const PET = parseFloat(item['市盈率(TTM)'])
            const PED = parseFloat(item['市盈率(动)'])
            if ([PEJ, PED, PET].every(el => !isNaN(el))) {
                if (PEJ > PET && PET > PED) {
                    item['PEJ/PET'] = PEJ / PET
                    item['PET/PED'] = PET / PED
                    list.push(item)
                }
            }
            await page.waitForTimeout(10)
        }
    } catch {

    } finally {
        const goodStock = list.filter(el => el['PEJ/PET'] > 1 && el['PET/PED'] > 1.2 && el['市盈率(静)'] < maxPE).map(el => ({
            '股票代码': el['股票代码'],
            '股票名称': el['股票名称'],
            '总市值(亿)': el['总市值'].replace('亿', ''),
            '当前股价': el['当前股价'],
            '今日涨幅': el['今日涨幅'],
            '52周最高': el['52周最高'],
            '52周最低': el['52周最低'],
            '市盈率(静)': el['市盈率(静)'],
            '市盈率(TTM)': el['市盈率(TTM)'],
            '市盈率(动)': el['市盈率(动)'],
            'PEJ/PET': el['PEJ/PET'],
            'PET/PED': el['PET/PED'],
        }))
        xls = json2xls(goodStock)
        fs.writeFileSync('./good-match-stock.xlsx', xls, 'binary')
        await browser.close()
    }
}
main()

JSON.stringify()